<!DOCTYPE html>
<html lang="zh-CN" color-mode=light>


<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>ExifTool 结合 Python 实现媒体文件创建时间批量自动修改 - 树朾的开源技术分享</title>
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="google" content="notranslate" />
  <meta name="keywords" content="开源, 分享">
  <meta name="description" content="本文详细介绍如何运用Python的自动化能力结合Exi...">
  <meta name="author" content="scwang90">
  <link rel="icon" href="/images/icons/favicon.ico">
  
  
  
  
  

  
<link rel="stylesheet" href="/css/style.css">


  
    
<link rel="stylesheet" href="https://at.alicdn.com/t/font_1445822_p6ry5n7lrr.css">

  

  
    
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css">

  

  
    
      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/xcode.min.css" name="highlight-style" mode="light">

      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/solarized-dark.min.css" name="highlight-style" mode="dark">

      
  

  <script>
    var CONFIG = window.CONFIG || {};
    var ZHAOO = window.ZHAOO || {};
    CONFIG = {
      isHome: false,
      fancybox: true,
      pjax: false,
      loading: {
        gif: '/images/theme/loading.gif',
        lottie: ''
      },
      lazyload: {
        enable: true,
        only_post: 'false',
        loading: {
          gif: '/images/theme/loading.gif',
          lottie: ''
        }
      },
      donate: {
        enable: false,
        alipay: '/images/donate/pay_alipay.jpg',
        wechat: '/images/donate/pay_wxpay.jpg',
        tencent: '/images/donate/pay_tencent.jpg'
      },
      galleries: {
        enable: true
      },
      fab: {
        enable: true,
        always_show: false
      },
      carrier: {
        enable: true
      },
      daovoice: {
        enable: false
      },
      preview: {
        background: {
          default: '',
          api: ''
        },
        motto: {
          default: '我在开了灯的床头下，想问问自己的心啊。',
          typing: true,
          api: 'https://v2.jinrishici.com/one.json',
          data_contents: '["data","content"]'
        },
      },
      qrcode: {
        enable: true,
        type: 'url',
        image: 'https://pic.izhaoo.com/weapp-code.jpg',
      },
      toc: {
        enable: true
      },
      scrollbar: {
        type: 'default'
      },
      notification: {
        enable: false,
        delay: 4500,
        list: '',
        page_white_list: '',
        page_black_list: ''
      },
      search: {
        enable: false,
        path: ''
      }
    }
  </script>

  

  

<meta name="generator" content="Hexo 6.2.0"></head>

<body class="lock-screen">
  <div class="loading" id="loading"></div>
  
    


  <nav class="navbar">
    <div class="left">
      
        <i class="iconfont iconhome j-navbar-back-home"></i>
      
      
        <i class="iconfont iconqrcode j-navbar-qrcode"></i>
      
      
        <i class="iconfont iconmoono" id="color-toggle" color-toggle="light"></i>
      
      
    </div>
    <div class="center">ExifTool 结合 Python 实现媒体文件创建时间批量自动修改</div>
    <div class="right">
      <i class="iconfont iconmenu j-navbar-menu"></i>
    </div>
    
      <div id="qrcode-navbar"></div>
    
  </nav>

  
  

<nav class="menu">
  <div class="menu-container">
    <div class="menu-close">
      <i class="iconfont iconbaseline-close-px"></i>
    </div>
    <ul class="menu-content"><li class="menu-item">
        <a href="/ " class="underline "> 首页</a>
      </li><li class="menu-item">
        <a href="/galleries/ " class="underline "> 摄影</a>
      </li><li class="menu-item">
        <a href="/archives/ " class="underline "> 归档</a>
      </li><li class="menu-item">
        <a href="/tags/ " class="underline "> 标签</a>
      </li><li class="menu-item">
        <a href="/categories/ " class="underline "> 分类</a>
      </li><li class="menu-item">
        <a href="/about/ " class="underline "> 关于</a>
      </li></ul>
    
      <div class="menu-copyright"><p>Powered by <a target="_blank" href="https://github.com/scwang90">scwang90</a>  |  Theme - <a target="_blank" href="https://github.com/izhaoo/hexo-theme-zhaoo">zhaoo</a></p> <p><a target="_blank" href="http://beian.miit.gov.cn/"><span>黔ICP备2021004317号-1</span></a><span>  |  </span><a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo" style="display:inline-block;text-decoration:none;height:20px;line-height:20px;"><img class="lazyload" data-original="/images/icons/icon-filing.png" src="https://www.beian.gov.cn/img/new/gongan.png"/> <span> 贵公网安备 52010202002539号</span></a></p></div>
    
  </div>
</nav>
  <main id="main">
  <div class="article-wrap">
    
      <div class="row container container-lg">
        <div class="col-xl-2"></div>
        <div class="col-xl-8"><article class="article">
  <div class="wrap">
    <section class="head">
  <img   class="lazyload" data-original="/images/theme/post-image.jpg" src=""  draggable="false">
  <div class="head-mask">
    <h1 class="head-title">ExifTool 结合 Python 实现媒体文件创建时间批量自动修改</h1>
    <div class="head-info">
      <span class="post-info-item"><i class="iconfont iconcalendar"></i>四月 26, 2024</span>
      
      <span class="post-info-item"><i class="iconfont iconfont-size"></i>3025</span>
    </div>
  </div>
</section>
    <section class="main">
      <section class="content article-entry">
        
          
            <p>本文详细介绍如何运用Python的自动化能力结合ExifTool的强大功能，实现媒体文件创建时间的批量自动修改。继之前对ExifTool的深入解析与实战介绍后，本文将聚焦于实际应用中的批量操作实践。</p>
          
        
        <p>在日常处理大量媒体文件时，我们可能遇到需要批量调整文件创建时间的情况。结合Python的高效自动化能力和ExifTool这款全能的元数据处理工具，我们可以轻松实现这一目标。本文将引导您通过编写Python脚本，利用ExifTool的强大功能批量自动修改媒体文件的创建时间。</p>
<h2 id="方法封装"><a href="#方法封装" class="headerlink" title="方法封装"></a><strong>方法封装</strong></h2><p>首先，我们需要封装两个关键函数：<code>get_media_creation_time()</code>用于提取媒体文件的当前创建时间，<code>set_media_creation_time()</code>用于设置新的创建时间。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> subprocess</span><br><span class="line"><span class="keyword">import</span> re, os</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">get_media_creation_time</span>(<span class="params">file_path</span>):</span><br><span class="line">    <span class="comment"># 使用 exiftool 提取视频的 MediaCreateDate</span></span><br><span class="line">    command = <span class="string">f&#x27;exiftool -MediaCreateDate &quot;<span class="subst">&#123;file_path&#125;</span>&quot;&#x27;</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        output = subprocess.check_output(command, shell=<span class="literal">True</span>).decode(<span class="string">&#x27;utf-8&#x27;</span>)</span><br><span class="line">        match = re.search(<span class="string">r&#x27;:\s*([\d\- :\.TZ]+)&#x27;</span>, output)</span><br><span class="line">        <span class="keyword">if</span> match:</span><br><span class="line">            <span class="keyword">return</span> match.group(<span class="number">1</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line">    <span class="keyword">except</span> subprocess.CalledProcessError <span class="keyword">as</span> e:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">f&quot;Error while running exiftool: <span class="subst">&#123;e&#125;</span>&quot;</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line">    </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">set_media_creation_time</span>(<span class="params">file_path, new_time</span>):</span><br><span class="line">    <span class="comment"># ExifTool 可以用来修改视频元数据</span></span><br><span class="line">    utc_command = <span class="string">f&#x27;exiftool -overwrite_original_in_place &quot;-MediaCreateDate=<span class="subst">&#123;new_time&#125;</span>&quot; &quot;<span class="subst">&#123;file_path&#125;</span>&quot;&#x27;</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        subprocess.run(utc_command, shell=<span class="literal">True</span>, check=<span class="literal">True</span>)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">f&quot;Media creation time successfully set to <span class="subst">&#123;new_time&#125;</span>.&quot;</span>)</span><br><span class="line">    <span class="keyword">except</span> subprocess.CalledProcessError <span class="keyword">as</span> e:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">f&quot;Error while setting media creation time with exiftool: <span class="subst">&#123;e&#125;</span>&quot;</span>)</span><br></pre></td></tr></table></figure>

<p>这两个函数利用<code>subprocess</code>模块调用ExifTool命令行工具，分别获取和设置媒体文件的<code>MediaCreateDate</code>属性。错误处理机制确保了在执行过程中遇到问题时能够及时反馈。</p>
<h2 id="脚本实现"><a href="#脚本实现" class="headerlink" title="脚本实现"></a><strong>脚本实现</strong></h2><p>接下来，我们将编写主程序<code>main()</code>，遍历指定目录下的媒体文件，并根据文件名中包含的日期信息（如果存在）来更新其创建时间。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">main</span>():</span><br><span class="line">    path = <span class="string">&#x27;/nas/videos/&#x27;</span>  <span class="comment"># 指定媒体文件所在目录</span></span><br><span class="line">    files = os.listdir(path)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> file <span class="keyword">in</span> files:</span><br><span class="line">        file_path = os.path.join(path, file)</span><br><span class="line">        <span class="keyword">if</span> os.path.isfile(file_path):</span><br><span class="line">            media_creation_time = get_media_creation_time(file_path)</span><br><span class="line">            </span><br><span class="line">            <span class="comment"># 检查是否为默认创建时间（&#x27;0000:00:00 00:00:00&#x27;），若为默认值则尝试从文件名中提取日期</span></span><br><span class="line">            <span class="keyword">if</span> media_creation_time == <span class="string">&#x27;0000:00:00 00:00:00&#x27;</span>:</span><br><span class="line">                date_pattern = <span class="string">r&#x27;^(\d&#123;4&#125;-\d&#123;2&#125;-\d&#123;2&#125;)&#x27;</span></span><br><span class="line">                match = re.match(date_pattern, file)</span><br><span class="line">                </span><br><span class="line">                <span class="keyword">if</span> match:</span><br><span class="line">                    extracted_date = match.group(<span class="number">1</span>)</span><br><span class="line">                    extracted_date = extracted_date.replace(<span class="string">&#x27;-&#x27;</span>, <span class="string">&#x27;:&#x27;</span>) + <span class="string">&#x27; 00:00:00&#x27;</span></span><br><span class="line">                    </span><br><span class="line">                    <span class="built_in">print</span>(<span class="string">f&quot;<span class="subst">&#123;file:&lt;<span class="number">40</span>&#125;</span> <span class="subst">&#123;media_creation_time&#125;</span> -&gt; <span class="subst">&#123;extracted_date&#125;</span>&quot;</span>)</span><br><span class="line">                    set_media_creation_time(file_path, extracted_date)</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>

<p>主程序<code>main()</code>按照以下步骤执行：</p>
<ol>
<li><strong>定义路径</strong>：设定要处理的媒体文件所在目录。</li>
<li><strong>获取文件列表</strong>：使用<code>os.listdir()</code>获取该目录下所有文件及子目录的名称。</li>
<li><strong>遍历文件</strong>：对每个文件进行判断，仅处理实际的文件（非目录）。</li>
<li><strong>检查并提取创建时间</strong>：检查当前文件的创建时间是否为默认值（’0000:00:00 00:00:00’）。如果是，则尝试从文件名中提取日期信息。</li>
<li><strong>格式化日期</strong>：将提取到的日期字符串（如<code>YYYY-MM-DD</code>）转换为ExifTool所需的格式（如<code>YYYY:MM:DD 00:00:00</code>）。</li>
<li><strong>设置创建时间</strong>：调用<code>set_media_creation_time()</code>函数，使用提取到的日期信息更新文件的创建时间，并输出操作结果。</li>
</ol>
<p>通过运行此脚本，您将能便捷地批量修改指定目录下媒体文件的创建时间，极大地提高了工作效率。同时，脚本中灵活的日期提取逻辑使得其适用于具有特定命名规则的文件集，增强了实用性。</p>

      </section>
      <section class="extra">
        
          <ul class="copyright">
  
    <li><strong>本文作者：</strong>scwang90</li>
    <li><strong>本文链接：</strong><a href="https://blog.scwang90.cn/2024/04/26/exiftool-python/index.html" title="https:&#x2F;&#x2F;blog.scwang90.cn&#x2F;2024&#x2F;04&#x2F;26&#x2F;exiftool-python&#x2F;index.html">https:&#x2F;&#x2F;blog.scwang90.cn&#x2F;2024&#x2F;04&#x2F;26&#x2F;exiftool-python&#x2F;index.html</a></li>
    <li><strong>版权声明：</strong>本分享所有文章均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" title="BY-NC-SA" target="_blank" rel="noopener">BY-NC-SA</a> 许可协议，转载请注明出处！</li>
  
</ul>
        
        
        
  <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/exiftool/" rel="tag">exiftool</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/python/" rel="tag">python</a></li></ul> 

        
  <nav class="nav">
    <a href="/2024/04/29/css-draw/"><i class="iconfont iconleft"></i>利用纯 CSS 绘制三角形</a>
    <a href="/2024/04/25/vue-route-lifecycle/">Vue 组件在路由跳转下的生命周期探究<i class="iconfont iconright"></i></a>
  </nav>

      </section>
      
    </section>
  </div>
</article></div>
        <div class="col-xl-2">
          
            
  <aside class="toc-wrap">
    <h3 class="toc-title">文章目录：</h3>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%B9%E6%B3%95%E5%B0%81%E8%A3%85"><span class="toc-text">方法封装</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%84%9A%E6%9C%AC%E5%AE%9E%E7%8E%B0"><span class="toc-text">脚本实现</span></a></li></ol>
  </aside>

          
        </div>
      </div>
    
  </div>
</main>
  

<footer class="footer">
  <div class="footer-social"><a 
        href="tencent://message/?Menu=yes&uin=283371828 "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#12B7F5'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconQQ "></i>
      </a><a 
        href="javascript:; "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#09BB07'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconwechat-fill "></i>
      </a><a 
        href="https://github.com/scwang90 "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#9f7be1'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  icongithub-fill "></i>
      </a><a 
        href="mailto:scwang90@hotmail.com "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color=#FF3B00" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconmail"></i>
      </a></div>
  
    <div class="footer-copyright"><p>Powered by <a target="_blank" href="https://github.com/scwang90">scwang90</a>  |  Theme - <a target="_blank" href="https://github.com/izhaoo/hexo-theme-zhaoo">zhaoo</a></p> <p><a target="_blank" href="http://beian.miit.gov.cn/"><span>黔ICP备2021004317号-1</span></a><span>  |  </span><a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo" style="display:inline-block;text-decoration:none;height:20px;line-height:20px;"><img class="lazyload" data-original="/images/icons/icon-filing.png" src="https://www.beian.gov.cn/img/new/gongan.png"/> <span> 贵公网安备 52010202002539号</span></a></p></div>
  
</footer>
  
      <div class="fab fab-plus">
    <i class="iconfont iconplus"></i>
  </div>
  
  
  
  <div class="fab fab-up">
    <i class="iconfont iconcaret-up"></i>
  </div>
  
  
  
    
<script src="/js/color-mode.js"></script>

  
  
</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>





  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>




  
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>






  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>




<script src="/js/utils.js"></script>
<script src="/js/script.js"></script>







  <script>
    (function () {
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      } else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>













</html>